package com.gaoyi.crm.vm;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.gaoyi.crm.R;
import com.gaoyi.crm.apiresult.ApiResultData;
import com.gaoyi.crm.apiresult.PagedList;
import com.gaoyi.crm.callback.OnResultListener;
import com.gaoyi.crm.constant.ApiStatus;
import com.gaoyi.crm.db.dto.SyncedItemDto;
import com.gaoyi.crm.db.query.CtmSyncedQuery;
import com.gaoyi.crm.repository.ItemNoStoreRepository;
import com.gaoyi.crm.util.ToastUtil;
import com.gaoyi.crm.vm.base.BaseListViewModel;

import java.util.List;

public class CtmSyncedItemNoViewModel extends BaseListViewModel<SyncedItemDto> {

    MutableLiveData<Integer> mTotal;
    ItemNoStoreRepository mRepository;

    public MutableLiveData<Integer> getTotal() {
        if (mTotal == null) {
            mTotal = new MutableLiveData<>();
        }
        return mTotal;
    }

    public CtmSyncedItemNoViewModel(@NonNull Application application) {
        super(application);
        mRepository = new ItemNoStoreRepository();
    }

    public void getSyncedItemNo(CtmSyncedQuery query) {
        mRepository.getSyncedItemNo(query, new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                ApiResultData<PagedList<SyncedItemDto>> apiResultData = (ApiResultData<PagedList<SyncedItemDto>>) apiResult;
                mResultCode.setValue(apiResultData.getStatus());
                if (apiResultData.getStatus() != ApiStatus.SUCCESS) {
                    ToastUtil.showToast(apiResultData.getMessage());
                    return;
                }
                PagedList<SyncedItemDto> data = apiResultData.getData();
                if (data != null) {
                    mTotal.setValue(data.getTotalCount());
                    List<SyncedItemDto> list = data.getList();
                    if (list != null && !list.isEmpty()) {
                        addListValue(list);
                    }
                }
            }

            @Override
            public void onFails(Exception e) {
                if (getView() != null) {
                    getView().hideLoading();
                }
                mResultCode.setValue(ApiStatus.NET_ERROR);
                ToastUtil.showToast(R.string.network_error);
            }
        });
    }
}
